<?php

class Session_Controller extends BaseController {
	protected $includePath;
	public function __construct(Request $request, Response $response, $method) {
		parent::__construct($request, $response, $method);
		if ($this->loginCheck() && !in_array($method, ['logout', 'changePassword', 'resetPassword'])) $response->redirect('/');
		if ($this->user) {
			switch ($this->user->type) {
				case User::TYPE_ADMINISTRATOR:
					$this->includePath = ROOT . '/view/admin/common/';
					break;
				case User::TYPE_STUDENT:
					$this->includePath = ROOT . '/view/common/student/';
					break;
				case User::TYPE_TEACHER:
					$this->includePath = ROOT . '/view/common/teacher/';
					break;
			}
		}
	}
	public function index(Request $request, Response $response) {
		//保留此空方法以避免返回404错误!!!
	}
	public function login(Request $request, Response $response) {
		if (!$request->isPost()) $response->send(new View('session/login'));
		$username = $request->username;
		$password = $request->password;
		$users = User::find(new Query('name', $username));
		if (count($users) == 0) $response->redirect('/session/login?fail=1');
		$user = array_values($users)[0];
		/**
		 * @var	User	$user
		 */
		//已经在数据库保证stuId字段为UNIQUE
		if ($user->password != $user->generatePassword($password)) $response->redirect('/session/login?fail=1');
		setcookie("_uid", $user->id, time()+86400, '/', ADMIN_HOST);
		setcookie("_uid", $user->id, time()+86400, '/', '*.'.ADMIN_HOST);
		setcookie("_secret", md5($user->id .'_ebf_'. $user->password), time()+86400, '/', ADMIN_HOST);
		setcookie("_secret", md5($user->id .'_ebf_'. $user->password), time()+86400, '/', '*.'.ADMIN_HOST);
		if ($user->type == User::TYPE_ADMINISTRATOR) $response->redirect('/admin/');
		else $response->redirect('/');
	}
	public function logout(Request $request, Response $response) {
		$this->clearCookie();
		$response->redirect('/');
	}
	public function changePassword(Request $request, Response $response) {
		$includePath = $this->includePath;
		if (!$request->isPost()) $response->send(new View('session/changePassword', compact('includePath')));
		$originPassword = $request->originPassword;
		$newPassword = $request->newPassword;
		if ($this->user->password != $this->user->generatePassword($originPassword)) $response->alertErrorAndGoBack('旧密码不正确！');
		$this->user->password = $this->user->generatePassword($newPassword);
		$this->user->save();
		$succ = 1;
		$response->send(new View('session/changePassword', compact('succ', 'includePath')));
	}
}